/**
 *
 *  License: http://www.apache.org/licenses/LICENSE-2.0
 *  Home page: https://github.com/linlurui/ccweb
 *  Note: to build on java, include the jdk1.8+ compiler symbol (and yes,
 *  I know the difference between language and runtime versions; this is a compromise).
 * @author linlurui
 * @Date Date: 2019-02-10
 */

package abc.listener;


import abc.base.BaseModel;
import abc.model.SheetHeaderModel;
import abc.utils.JacksonUtil;
import abc.utils.ReflectionUtil;
import abc.utils.StringUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模板的读取类
 */
// 有个很重要的点 HashMapListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
public class ExcelListener extends AnalysisEventListener<Object> {
    private static final Logger logger = LoggerFactory.getLogger(ExcelListener.class);
    /**
     * 每隔500条存储数据库，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 500;
    private final List<SheetHeaderModel> headerList;
    private final Object entity;
    private final List<String> pkList;

    List<Object> list = new ArrayList<Object>();
    String tablename;
    private boolean first = true;
    private boolean retryLock;

    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     */
    public ExcelListener(String tablename, Object entity, List<SheetHeaderModel> headerList, List<String> pkList) throws Exception {
        this.entity = entity;
        this.headerList = headerList;
        this.tablename = tablename;
        this.pkList = pkList;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data
     *            one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(Object data, AnalysisContext context) {

        ReadSheet readSheet = new ReadSheet();
        if("schema".equals(readSheet.getSheetName())){
            return;
        }

        list.add(data);

        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        retryLock = true;
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }

    /**
     * 读取表头内容
     * @param headMap   表头部数据
     * @param context   数据解析上下文
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        //System.out.println("表头：" + headMap);
    }

    /**
     * 解析过程如果发生异常，会调用此方法
     * @param exception
     * @param context
     */
    @Override
    public void onException(Exception exception, AnalysisContext context){
        throw new RuntimeException("Excel数据异常，请检查或联系管理员！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        logger.info("easyexcel: {}条数据，开始导入数据库！", list.size());
        for(Object obj : list) {

            try {
                Map<String, Object> postData = new HashMap<String, Object>();
                for(SheetHeaderModel headerModel : headerList) {
                    if(pkList.contains(headerModel.getField())) {
                        continue;
                    }
                    Object value = ReflectionUtil.getFieldValue(obj, getFieldName(headerModel.getField()));
                    postData.put(headerModel.getField(), value);
                }

                BaseModel model = (BaseModel) JacksonUtil.convert(postData, entity.getClass());

                model.insert();

            } catch (Exception e) {
                logger.error("插入数据失败：" + e.getMessage());
                e.printStackTrace();
            }
        }
        logger.info("导入数据库成功！");
    }

    private String getFieldName(String field) {
        List<String> list = StringUtil.splitString2List(field, "_");
        for(int i=0; i<list.size(); i++) {
            String value = list.get(i);
            if(i==0) {
                list.set(i, value.substring(0, 1).toLowerCase() + value.substring(1));
                continue;
            }

            list.set(i, value.substring(0, 1).toUpperCase() + value.substring(1));
        }

        String result = StringUtil.join("", list);

        return result;
    }
}
